﻿using Newtonsoft.Json;
using System.Net;

namespace GGGK.Film.Api.Comm
{
    public class ExceptionHandlerMiddleWare
    {
        private readonly RequestDelegate next;
        private static readonly ILogger<ExceptionHandlerMiddleWare> logger;

        public ExceptionHandlerMiddleWare(RequestDelegate next, ILogger<ExceptionHandlerMiddleWare> logger)
        {
            this.next = next;
            logger = logger;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await next(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }
        }

        private static async Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            if (exception == null) return;
            await WriteExceptionAsync(context, exception).ConfigureAwait(false);
        }

        private static async Task WriteExceptionAsync(HttpContext context, Exception exception)
        {
            // 记录日志
            logger.LogError(exception.GetBaseException().ToString());

            var response = context.Response;

            // 状态码
            if (exception is UnauthorizedAccessException)
                response.StatusCode = (int)HttpStatusCode.Unauthorized;
            else if (exception is Exception)
                response.StatusCode = (int)HttpStatusCode.BadRequest;

            response.ContentType = "application/json";
            await response.WriteAsync(JsonConvert.SerializeObject(new { code = -1, msg = exception.Message })).ConfigureAwait(false);
        }
    }
}
